package com.tcpudp.service;

import com.tcpudp.model.Connection;
import com.tcpudp.model.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
public class ConnectionService {
    private static final Logger log = LoggerFactory.getLogger(ConnectionService.class);
    
    private final Map<String, Connection> connections = new ConcurrentHashMap<>();
    private final WebSocketService webSocketService;

    public ConnectionService(WebSocketService webSocketService) {
        this.webSocketService = webSocketService;
    }

    public Connection addConnection(String serverId, String remoteAddress, int remotePort) {
        Connection connection = new Connection();
        connection.setServerId(serverId);
        connection.setRemoteAddress(remoteAddress);
        connection.setRemotePort(remotePort);
        
        connections.put(connection.getId(), connection);
        
        // 通知Web客户端
        webSocketService.broadcastMessage(Map.of(
            "type", "CONNECTION_ADDED",
            "connection", connection
        ));
        
        return connection;
    }

    public void removeConnection(String connectionId) {
        Connection connection = connections.get(connectionId);
        if (connection != null) {
            connection.setActive(false);
            
            // 通知Web客户端
            webSocketService.broadcastMessage(Map.of(
                "type", "CONNECTION_REMOVED",
                "connectionId", connectionId
            ));
        }
    }

    public void addMessage(String connectionId, String content, String direction, String contentType) {
        Connection connection = connections.get(connectionId);
        if (connection != null) {
            Message message = new Message();
            message.setConnectionId(connectionId);
            message.setContent(content);
            message.setDirection(direction);
            message.setContentType(contentType);
            
            connection.getMessages().add(message);
            
            // 通知Web客户端
            webSocketService.broadcastMessage(Map.of(
                "type", "MESSAGE_ADDED",
                "connectionId", connectionId,
                "message", message
            ));
        }
    }

    public List<Connection> getConnectionsByServerId(String serverId) {
        return connections.values().stream()
                .filter(conn -> conn.getServerId().equals(serverId) && conn.isActive())
                .collect(Collectors.toList());
    }

    public List<Connection> getAllConnections() {
        return new ArrayList<>(connections.values());
    }

    public Connection getConnection(String connectionId) {
        return connections.get(connectionId);
    }
}